<template>
  <a-card :bordered="false">
    <div style="margin-bottom:10px">
      <a-button icon="plus" type="primary" @click="handleAdd" style="margin-right:10px;">新增商家</a-button>
      <a-upload
        name="file"
        :showUploadList="false"
        :multiple="false"
        :headers="tokenHeader"
        :action="importExcelUrl"
        :beforeUpload="beforeUpload"
        @change="handleImportExcel"
        accept=".xls, .xlsx"
      >
        <a-button type="primary" icon="import" :loading="loading">批量上传</a-button>
      </a-upload>
    </div>
    <div>
      <a-table
        ref="table"
        bordered
        size="middle"
        :loading="loading"
        :columns="columns"
        :dataSource="dataSource"
        rowKey="id"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template slot="img" slot-scope="text,record,index">
          <div style="width:60px;height:60px;margin:0 auto">
            <img :src="record.idPic" alt style="width:100%;height:100%" />
          </div>
        </template>
        <template slot="intro" slot-scope="text,record,index">
          <span class="sihang">{{record.intro}}</span>
        </template>
        <template slot="action" slot-scope="text,record,index">
          <div>
            <a-button
              type="primary"
              icon="edit"
              @click="handleEdit(record)"
              style="margin-right:10px;"
            >编辑</a-button>
            <a-popconfirm
              placement="top"
              :title="confirm_title"
              @confirm="confirm(record)"
              okText="Yes"
              cancelText="No"
            >
              <a-button type="danger" icon="delete">删除</a-button>
            </a-popconfirm>
          </div>
        </template>
      </a-table>
    </div>
    <a-modal
      :title="modal_title"
      :visible="modal_visible"
      :confirmLoading="loading"
      width="60%"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form :form="form">
        <a-form-item label="ID" :labelCol="labelCol" :wrapperCol="wrapperCol" style="display:none">
          <a-input v-decorator="['id']" style="display:none" :disabled="true"></a-input>
        </a-form-item>
        <a-form-item label="商家名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            v-decorator="['name',{rules:[{required:true,message:'商家名称'}]}]"
            placeholder="商家名称"
          ></a-input>
        </a-form-item>
        <a-form-item label="商家拼音(首字单个拼音)" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            v-decorator="['smallName']"
            placeholder="商家拼音（首字单个拼音，如a）"
            oninput="this.value=this.value.replace(/[\u4e00-\u9fa5\d]/g,'');"
            maxlength="1"
          ></a-input>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排序">
          <a-input
            v-decorator="['sort']"
            placeholder="排序"
            oninput="value=value.replace(/[^\d]/g,'')"
          ></a-input>
        </a-form-item>
        <a-form-item label="营业执照号" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['idNo']" placeholder="营业执照号"></a-input>
        </a-form-item>
        <a-form-item label="营业执照图" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload
            :action="modal_action"
            listType="picture-card"
            :fileList="fileList"
            @preview="handlePreview"
            @change="handleChange"
            :beforeUpload="beforeUpload"
            accept=".jpg, .png, .jpeg, .JPG, .PNG, .JPEG"
          >
            <div v-if="fileList.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
          <a-input v-decorator="['idPic']" placeholder="营业执照图" :disabled="true"></a-input>
        </a-form-item>
        <a-form-item label="商家地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['address']" placeholder="商家地址"></a-input>
        </a-form-item>
        <a-form-item label="联系电话" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['tel']" placeholder="联系电话"></a-input>
        </a-form-item>
        <a-form-item label="商家介绍" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input v-decorator="['intro']" placeholder="商家介绍" style="display:none" :disabled="true"></a-input>
          <tinymce-editor ref="editor" v-model="msg" @onClick="onClick"></tinymce-editor>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import { postAction, baseUrl } from '@/api/manage.js'
import TinymceEditor from '@/components/TinyEditor/tiny-editor'

export default {
  data() {
    return {
      loading: false,
      pagination: {
        total: 0,
        pageSize: 10,
        current: 1,
        showTotal: total => `共有 ${total} 条数据` //分页中显示总的数据
      },
      columns: [
        { title: 'ID', align: 'center', dataIndex: 'id' },
        { title: '商家名称', align: 'center', dataIndex: 'name', width: 200 },
        { title: '排序', align: 'center', dataIndex: 'sort' },
        { title: '营业执照号', align: 'center', dataIndex: 'idNo' },
        { title: '营业执照图', align: 'center', scopedSlots: { customRender: 'img' } },
        { title: '商家介绍', align: 'center', width: 200, scopedSlots: { customRender: 'intro' } },
        { title: '商家地址', align: 'center', dataIndex: 'address' },
        { title: '联系电话', align: 'center', dataIndex: 'tel' },
        { title: '操作', align: 'center', scopedSlots: { customRender: 'action' } }
      ],
      dataSource: [],
      confirm_title: '确定要删除此类型?',
      modal_title: '',
      modal_visible: false,
      form: this.$form.createForm(this), // 只有这样注册后，才能通过表单拉取数据
      labelCol: {
        lg: {
          span: 7
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        lg: {
          span: 10
        },
        sm: {
          span: 17
        }
      },
      modal_action: `${baseUrl}/file/uploadImg`,
      fileList: [],
      tokenHeader: {
        authorization: 'authorization-text'
      },
      importExcelUrl: `${baseUrl}/merchant/adds`,
      msg: ''
    }
  },
  components: {
    TinymceEditor
  },
  created() {
    this.getData()
  },
  methods: {
    getData() {
      this.loading = true
      postAction('/merchant/page', {
        page: this.pagination.current,
        size: this.pagination.pageSize
      }).then(res => {
        this.loading = false
        // console.log(res)
        this.dataSource = res.data
        const pagination = { ...this.pagination }
        pagination.total = res.total
        this.pagination = pagination
      })
    },
    handleTableChange(pagination) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getData()
    },
    handleEdit(item) {
      this.modal_title = '编辑商家'
      this.msg = item.intro
      const obj = {
        uid: '-1',
        name: 'xxx.png',
        status: 'done',
        url: item.idPic
      }
      this.fileList.push(obj)
      setTimeout(() => {
        this.form.setFieldsValue({
          id: item.id,
          name: item.name,
          smallName: item.smallName,
          idNo: item.idNo,
          idPic: item.idPic,
          address: item.address,
          tel: item.tel,
          sort: item.sort
        })
      })
      this.modal_visible = true
    },
    confirm(item) {
      this.loading = true
      postAction('/merchant/delete', {
        id: item.id
      }).then(res => {
        this.loading = false
        if (this.dataSource.length == 1) {
          this.pagination.current--
        }
        if (this.pagination.current == 1) {
          this.pagination.current = 1
        }
        this.getData()
      })
    },
    handleOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.loading = true
          this.form.setFieldsValue({
            intro: this.msg
          })
          postAction('/merchant/add', this.form.getFieldsValue()).then(res => {
            this.loading = false
            this.msg = ''
            this.form.resetFields()
            this.modal_visible = false
            this.fileList = []
            this.getData()
          })
        }
      })
    },
    handleCancel() {
      this.msg = ''
      this.fileList = []
      this.form.resetFields()
      this.modal_visible = false
    },
    handleAdd() {
      this.msg = ''
      this.modal_title = '新增商家'
      this.modal_visible = true
    },
    //点击预览图标时的回调
    handlePreview(file) {},
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
      if (!isJPG) {
        this.$message.error('仅支持jpeg/png/jpg格式!')
      }
      // const isLt2M = file.size / 1024 / 1024 < 5
      // if (!isLt2M) {
      //   this.$message.error('上传不能超过5MB!')
      // }
      return isJPG
    },
    //上传文件改变时的状态
    handleChange({ file, fileList }) {
      this.fileList = fileList
      if (file.status == 'done') {
        fileList = fileList.map(item => {
          this.form.setFieldsValue({
            idPic: item.response.data
          })
        })
      } else if (file.status == 'removed') {
        this.form.setFieldsValue({
          idPic: ''
        })
      }
    },
    handleImportExcel({ file, fileList }) {
      this.loading = true
      if (file.status == 'done') {
        this.loading = false
        fileList = fileList.map(item => {
          if (item.response.code == 0 && item.response.status == 0) {
            this.getData()
          }
          this.$message.info(item.response.msg)
        })
      } else {
        this.loading = false
      }
    },
    beforeUpload(file) {
      const isJPG =
        file.type === 'application/vnd.ms-excel' ||
        file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isJPG) {
        this.loading = false
        this.$message.error('仅支持xls/xlsx格式!')
      }
      // const isLt2M = file.size / 1024 / 1024 < 5
      // if (!isLt2M) {
      //   this.$message.error('上传不能超过5MB!')
      // }
      return isJPG
    },
    onClick(e, t) {
      // console.log(e)
      // console.log(t)
    }
  }
}
</script>

<style lang="scss" scoped>
.sihang {
  overflow: hidden; /*超出部分隐藏*/
  text-overflow: ellipsis; /*溢出用省略号显示*/
  display: -webkit-box; /*将对象作为弹性伸缩盒子模型显示*/
  -webkit-box-orient: vertical; /*从上到下垂直排列子元素（设置伸缩盒子的子元素排列方式）*/
  -webkit-line-clamp: 4; /*这个属性不是css的规范属性，需要组合上面两个属性，表示显示的行数*/

  // overflow: hidden;
  // text-overflow: ellipsis;
  // white-space: nowrap;
  // display: inline-block;
  width: 400px;
  height: 80px;
}
</style>